﻿using System;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries.Comments {
    public partial class Create : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
            GetUsers();

            CheckEnquiry();
        }

        private void CheckEnquiry() {
            SendToFixYourStreetCaption.Visible = false;
            SendToFixYourStreet.Visible = false;
            CompletesCommitmentCaption.Visible = false;
            CompletesCommitment.Visible = false;

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null) {
                return;
            }
            
            if (enquiry.CommitmentClosure != null) {
                CompletesCommitmentCaption.Visible = true;
                CompletesCommitment.Visible = true;
            }

            if (enquiry.FixYourStreetId <= 0) {
                return;
            }

            SendToFixYourStreetCaption.Visible = true;
            SendToFixYourStreet.Visible = true;
        }

        private void GetUsers() {
            var users = UserRepository.QueryOver().Where(u => u.IsActive).OrderBy(u => u.DisplayName).Asc.List();
            BindDropDownList(OtherUsers, users, "DisplayName", "Id", "--Select--", "0");
        }

        protected void SubmitCommentClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null) {
                SubmitCommentResultMessage.Text = "Error enquiry not found!";
                return;
            }

            User otherUser = null;
            if (OtherUsers.SelectedIndex > 0) {
                otherUser = UserRepository.GetById(int.Parse(OtherUsers.SelectedItem.Value));                
            }
            var viewUrl = ConfigSettings.SiteRoot + "Enquiries/View.aspx?id=" + enquiryId;

            var comment = enquiry.AddComment(LoggedUser, CommentDetail.Text,
                                             SendToFixYourStreet.Checked, CompletesCommitment.Checked,
                                             NotifySubmitter.Checked, otherUser, viewUrl);

            if (!IsValidObject(comment, SubmitCommentResultMessage)) {
                return;
            }

            EnquiryRepository.Update(enquiry);

            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }
    }
}